package com.xb.cloud.shopping.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.xb.cloud.common.JsonUtils;
import com.xb.cloud.common.model.ShopType;
import com.xb.cloud.common.util.BeanUtils;
import com.xb.cloud.gateway.client.ReturnCodes;
import com.xb.cloud.gateway.client.ReturnUtils;
import com.xb.cloud.gateway.client.RtnInfo;
import com.xb.cloud.order.service.client.PaymentService;
import com.xb.cloud.order.service.client.ProductStockService;
import com.xb.cloud.order.service.client.SellOrderService;
import com.xb.cloud.order.service.client.bo.SellOrderBo;
import com.xb.cloud.order.service.client.bo.SellOrderOperationBo;
import com.xb.cloud.product.merchant.service.client.bo.ShopSkuBo;
import com.xb.cloud.product.service.client.CommonAddressService;
import com.xb.cloud.product.service.client.SkuService;
import com.xb.cloud.product.service.client.bo.AddressBo;
import com.xb.cloud.service.client.ServiceReturnInfo;
import com.xb.cloud.service.client.ServiceReturnUtils;
import com.xb.cloud.shopping.client.vo.CheckOutInputVo;
import com.xb.cloud.shopping.client.vo.ShopSkuCartItemVo;
import com.xb.cloud.shopping.client.vo.SkuCartItemVo;
import com.xb.cloud.shopping.client.vo.UserAddressVo;
import com.xb.cloud.shopping.model.OrderAccount;
import com.xb.cloud.shopping.model.ShoppingCartItem;
import com.xb.cloud.shopping.service.OrderSplitService;
import com.xb.cloud.shopping.service.OrderValidatorService;
import com.xb.cloud.shopping.service.ShoppingOrderApiService;
import com.xb.cloud.shopping.service.client.vo.PaymentRequestVo;
import com.xb.cloud.user.service.client.EndUserAddressService;
import com.xb.cloud.user.service.client.ShoppingCartService;
import com.xb.cloud.user.service.client.bo.EndUserAddressBo;
import com.xb.cloud.user.service.client.bo.EndUserCartBo;

@Service
public class ShoppingOrderApiServiceImpl implements ShoppingOrderApiService {

	@Resource
	SkuService skuService;
	@Resource
	ProductStockService productStockService;

	@Resource
	ShoppingCartService shoppingCartService;
	@Resource
	SellOrderService sellOrderService;

	@Resource
	EndUserAddressService endUserAddressService;
	@Resource
	CommonAddressService commonAddressService;

	@Resource
	OrderValidatorService orderValidatorService;
	@Resource
	OrderSplitService oeOrderSplitService;

	/**
	 * 
	 * 生成订单确认页面 <br/>
	 * 
	 * 确认下单之前进行验证： <br/>
	 * 1. 验证参数中的sku和数据库中购物车信息是否相同 <br/>
	 * 2. sku是否可售（下架或删除）<br/>
	 * 3. sku是否库存足够 <br/>
	 * 4. 校验sku前台显示价格和数据库价格是否相同，价格是否改变过 <br/>
	 * 5. //TODO: 销售区域的检查 <br/>
	 * 
	 * @param cartCheckOutVo
	 * @return
	 * @see com.xb.cloud.shopping.service.ShoppingOrderApiService#createAccountPage(com.xb.cloud.shopping.client.vo.CheckOutInputVo)
	 */
	@Override
	public RtnInfo createAccountPage(CheckOutInputVo cartCheckOutVo) {

		// 验证下单商品的购物车信息
		RtnInfo validateShoppingCartInfo = orderValidatorService.validateShoppingCartInfo(cartCheckOutVo);
		if (ReturnUtils.isError(validateShoppingCartInfo)) {
			return validateShoppingCartInfo;
		}

		List<ShoppingCartItem> checkoutitemList = cartCheckOutVo.getItemList();
		List<Long> skuIdList = new ArrayList<>();
		for (ShoppingCartItem checkoutItem : checkoutitemList) {
			skuIdList.add(checkoutItem.getSkuId());
		}
		List<ShopSkuBo> skuList = skuService.getShopSkuListBySkuIds(skuIdList);

		// 验证sku是否有效
		RtnInfo checkSkusCanSale = orderValidatorService.checkSkusCanSale(cartCheckOutVo, checkoutitemList, skuList);
		if (ReturnUtils.isError(checkSkusCanSale)) {
			return checkSkusCanSale;
		}
		

		OrderAccount orderAccount = new OrderAccount();
		
		// TODO:一期没有收货地址， 用户默认收货地址
//		long companyId = cartCheckOutVo.getCompanyId();
//		long endUserId = cartCheckOutVo.getCurrentUserId();
//		UserAddressVo defaultAddress = getUserDefaultAddress(companyId, endUserId);
//		if (defaultAddress != null) {
//			orderAccount.setHasDefaultAddress(true);
//			orderAccount.setDefaultAddress(defaultAddress);
//		}

		Map<Long, ShopSkuBo> skuMap = new HashMap<>();
		for (ShopSkuBo shopSkuBo : skuList) {
			skuMap.put(shopSkuBo.getSkuId(), shopSkuBo);
		}

		List<ShopSkuCartItemVo> shopSkuItemList = new ArrayList<>();
		Map<Long, ShopSkuCartItemVo> shopSkuItemMap = new HashMap<>();

		int count = 0;
		BigDecimal totalSkuAmount = BigDecimal.valueOf(0);
		for (ShoppingCartItem shoppingCartItem : checkoutitemList) {
			count += shoppingCartItem.getNum();
			Long skuId = shoppingCartItem.getSkuId();
			ShopSkuBo shopSkuBo = skuMap.get(skuId);
			BigDecimal priceSale = shopSkuBo.getPriceSale();
			BigDecimal skuAmount = priceSale.multiply(BigDecimal.valueOf(shoppingCartItem.getNum()));
			totalSkuAmount = totalSkuAmount.add(skuAmount);// 计算商品总价格

			ShopSkuCartItemVo shopSkuCartItemVo = shopSkuItemMap.get(shopSkuBo.getShopId());
			List<SkuCartItemVo> skuItems = null;

			if (shopSkuCartItemVo == null) {
				shopSkuCartItemVo = new ShopSkuCartItemVo();
				// 店铺信息
				shopSkuCartItemVo.setShopId(String.valueOf(shopSkuBo.getShopId()));
				shopSkuCartItemVo.setShopHomeUrl(shopSkuBo.getShopHomeUrl());
				shopSkuCartItemVo.setShopLogoUrl(shopSkuBo.getShopLogoUrl());
				shopSkuCartItemVo.setShopNameCn(shopSkuBo.getShopNameCn());
				String shopTypeName = "";
				if (shopSkuBo.getShopType() != null) {
					int shopType = shopSkuBo.getShopType();
					shopTypeName = ShopType.getEnumByCode(shopType).getName();
				}
				shopSkuCartItemVo.setShopType(shopTypeName);
				shopSkuItemMap.put(shopSkuBo.getShopId(), shopSkuCartItemVo);
				shopSkuItemList.add(shopSkuCartItemVo);

				// 店铺商品信息
				skuItems = new ArrayList<>();
				SkuCartItemVo skuCartItemVo = BeanUtils.newAndCopyProperties(SkuCartItemVo.class, shopSkuBo);
				skuCartItemVo.setNum(shoppingCartItem.getNum());
				skuItems.add(skuCartItemVo);
				shopSkuCartItemVo.setItems(skuItems);
			} else {
				skuItems = shopSkuCartItemVo.getItems();
				SkuCartItemVo skuCartItemVo = BeanUtils.newAndCopyProperties(SkuCartItemVo.class, shopSkuBo);
				skuCartItemVo.setNum(shoppingCartItem.getNum());
				skuItems.add(skuCartItemVo);
			}

		}

		orderAccount.setSkuAmount(totalSkuAmount);
		// TODO:计算订单总金额，需要考虑运费，满减，促销，商品券等。。。
		orderAccount.setOrderAmount(totalSkuAmount);
		// TODO:运费后期需要修改，由运费模板计算
		orderAccount.setDeliveryFee(BigDecimal.valueOf(0));

		orderAccount.setCount(count);// 下单商品总数
		orderAccount.setShopSkuItemList(shopSkuItemList);

		return ReturnUtils.success(orderAccount);
	}

	/**
	 * 生成订单
	 * 
	 * @Title generateOrder
	 * @param cartCheckOutVo
	 * @return
	 */
	@Override
	public RtnInfo generateOrder(CheckOutInputVo cartCheckOutVo) {
		// Long addressId = cartCheckOutVo.getAddressId();
		// if (addressId == null) {
		// return ReturnUtils.error(ReturnCodes.NEED_ORDER_ADDRESS);
		// }

		// 验证下单商品的购物车信息
		// RtnInfo validateShoppingCartInfo =
		// orderValidatorService.validateShoppingCartInfo(cartCheckOutVo);
		// if (ReturnUtils.isError(validateShoppingCartInfo)) {
		// return validateShoppingCartInfo;
		// }

		// EndUserAddressBo selectedAddress =
		// endUserAddressService.getUserAddressById(addressId);
		// if (selectedAddress == null || selectedAddress.getIsDeleted() ||
		// !selectedAddress.getIsEnabled()) {
		// return ReturnUtils.error(ReturnCodes.ORDER_ADDRESS_INVALID);
		// }

		List<ShoppingCartItem> checkoutitemList = cartCheckOutVo.getItemList();
		List<Long> skuIdList = new ArrayList<>();
		for (ShoppingCartItem checkoutItem : checkoutitemList) {
			skuIdList.add(checkoutItem.getSkuId());
		}
		List<ShopSkuBo> skuList = skuService.getShopSkuListBySkuIds(skuIdList);

		// 验证sku是否有效
		RtnInfo checkSkusCanSale = orderValidatorService.checkSkusCanSale(cartCheckOutVo, checkoutitemList, skuList);
		if (ReturnUtils.isError(checkSkusCanSale)) {
			return checkSkusCanSale;
		}

		Map<Long, ShopSkuBo> skuMap = new HashMap<>();
		for (ShopSkuBo shopSkuBo : skuList) {
			skuMap.put(shopSkuBo.getSkuId(), shopSkuBo);
		}

		// TODO: 一期不需要用户选择收货地址
		// 按店铺进行拆单
		List<SellOrderBo> orderList = oeOrderSplitService.splitOrder(cartCheckOutVo, skuMap, null);

		// 获取移除下单的商品后的购物车
		EndUserCartBo endUserCart = removeShoppingCartItems(cartCheckOutVo, skuIdList);
		SellOrderBo orderBo = sellOrderService.generateOrder(orderList, endUserCart);

		return ReturnUtils.success(orderBo);
	}

	@Override
	public RtnInfo cancelOrder(SellOrderOperationBo operationBo) {
		ServiceReturnInfo serviceReturnInfo = null;
		try {

			serviceReturnInfo = sellOrderService.cancelOrderbyEndUser(operationBo);
		} catch (Exception e) {
			return ReturnUtils.error(ReturnCodes.OEDER_CANCEL_ERROR);
			
		}
		if (ServiceReturnUtils.isSuccess(serviceReturnInfo)) {
			return ReturnUtils.success(serviceReturnInfo.getData());
		} else {
			return ReturnUtils.error(ReturnCodes.OEDER_CANCEL_FAILED);
		}
	}

	/**
	 * 获取用户默认收货地址
	 * 
	 * @Title getUserDefaultAddress
	 * @param companyId
	 * @param endUserId
	 * @return
	 */
	private UserAddressVo getUserDefaultAddress(long companyId, long endUserId) {
		EndUserAddressBo defaultAddress = endUserAddressService.getDefaultAddress(companyId, endUserId);
		if (defaultAddress != null) {
			Long countyId = defaultAddress.getCountyId();
			AddressBo addressBo = commonAddressService.getDetailsByCountyId(countyId);
			UserAddressVo userAddressVo = new UserAddressVo();
			userAddressVo.setId(defaultAddress.getId());
			userAddressVo.setPhone(defaultAddress.getPhone());
			userAddressVo.setIsDefault(defaultAddress.getIsDefault());
			userAddressVo.setReceiverName(defaultAddress.getReceiverName());
			userAddressVo.setAddressNickName(defaultAddress.getAddressNickName());
			String detailAddress = defaultAddress.getAddress();
			if (addressBo != null) {
				detailAddress = new StringBuffer(addressBo.getProvinceName()).append(addressBo.getCityName())
						.append(addressBo.getCountyName()).append(detailAddress).toString();

			}
			userAddressVo.setDetailAddress(detailAddress);
			return userAddressVo;
		}
		return null;
	}

	/**
	 * 
	 * @Title removeShoppingCartItems
	 * @param cartCheckOutVo
	 * @param skuIdList
	 * @return
	 */
	private EndUserCartBo removeShoppingCartItems(CheckOutInputVo cartCheckOutVo, List<Long> skuIdList) {
		EndUserCartBo endUserCartBo = new EndUserCartBo();
		endUserCartBo.setCompanyId(cartCheckOutVo.getCompanyId());
		endUserCartBo.setEndUserId(cartCheckOutVo.getCurrentUserId());
		EndUserCartBo endUserCart = shoppingCartService.getEndUserCart(endUserCartBo);
		String cartValues = endUserCart.getCartValues();
		List<ShoppingCartItem> skuItemList = JsonUtils.toObjectArray(cartValues, ShoppingCartItem.class);
		Iterator<ShoppingCartItem> iterator = skuItemList.iterator();
		while (iterator.hasNext()) {
			ShoppingCartItem item = iterator.next();
			if (skuIdList.contains(item.getSkuId())) {
				iterator.remove();
			}
		}
		String shoppingCartJson = JsonUtils.beanToJson(skuItemList);
		endUserCart.setCartValues(shoppingCartJson);
		return endUserCart;
	}

	@Override
	public RtnInfo deleteOrder(SellOrderOperationBo operationBo) {
		ServiceReturnInfo serviceReturnInfo = null;
		try {
			serviceReturnInfo = sellOrderService.deleteOrderbyEndUser(operationBo);
		} catch (Exception e) {
			e.printStackTrace();
			return ReturnUtils.error(ReturnCodes.OEDER_DELETE_ERROR);
		}
		
		if (ServiceReturnUtils.isSuccess(serviceReturnInfo)) {
			return ReturnUtils.success(serviceReturnInfo.getData());
		} else {
			return ReturnUtils.error(ReturnCodes.OEDER_DELETE_ERROR);
		}
	}

}
